<?php
use adminmatrix\migration\Migrator;
use  adminmatrix\migration\db\Column;
use Phinx\Db\Adapter\AdapterInterface;

class AdminRbac extends Migrator
{
    /**
    * Change Method.
    *
    * Write your reversible migrations using this method.
    *
    * More information on writing migrations is available here:
    * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
    *
    * The following commands can be used in this method and Phinx will
    * automatically reverse them when rolling back:
    *
    *    createTable
    *    renameTable
    *    addColumn
    *    renameColumn
    *    addIndex
    *    addForeignKey
    *
    * Remember to call "create()" or "update()" and NOT "save()" when working
    * with the Table class.
    */
   public function up()
   {
        // 创建管理员表
        $this->createAdminUserTable();

        // 创建管理员角色表
        $this->createAdminRole();

        // 创建管理员会话表
        $this->createAdminSession();

        // 创建管理员权限表
        $this->createAdminPermission();

        // 创建管理员与月色关联表
        $this->createAdminRoles();

        $this->createAdminRoles();

        $this->createRolePermissionTable();
        
   }

   public function down(){
       $this->output->writeln("== 执行删除管理员表");
       $admin = $this->table('admin')->drop()->save();
       $this->output->writeln("== 执行删除管理员角色表");
       $this->table('admin_role')->drop()->save();


       $this->output->writeln("== 执行删除管理员会话表");
       $this->table('admin_session')->drop()->save();

       $this->output->writeln("== 执行删除管理员权限表");
       $this->table('admin_permission')->drop()->save();

       $this->output->writeln("== 执行删除管理员关联角色表");
       $this->table('admin_roles')->drop()->save();
   }

    private function createRolePermissionTable()
    {

        if($this->hasTable('admin_role_permission'))
        {
            return $this->output->error("=== 角色权限关联表已存在 === 跳过");
        }

        $startTime = microtime(true);

        $table = $this->table('admin_role_permission', [
            'engine' => 'InnoDB',
            'collation' => 'utf8mb4_general_ci',
            'comment' => '角色权限关联表',
            'id' => false,
        ]);

        $table
            ->addColumn('role_id', 'integer', [
                'null' => false,
                'limit' => 11,
                'comment' => '角色 ID'
            ])
            ->addColumn('permission_id', 'integer', [
                'null' => false,
                'limit' => 11,
                'comment' => '权限 ID'
            ]);

        $table->addIndex(['role_id', 'permission_id'], [
            'name' => 'role_permission_index',
            'unique' => false
        ]);

        $table->create();

        // 记录结束时间
        $endTime = microtime(true);
        // 计算执行时间（秒）
        $executionTime = $endTime - $startTime;
        $executionTime = number_format($executionTime, 6, '.', '');
        $this->output->info("== 创建角色权限关联表完成用时：{$executionTime}秒");
    }

   private function createAdminRoles()
   {
       if($this->hasTable('admin_roles'))
       {
           return $this->output->error("=== 管理员关联角色表已存在 === 跳过");
       }
       $startTime = microtime(true);
       $table = $this->table('admin_roles', [
           'engine' => 'InnoDB',
           'collation' => 'utf8mb4_general_ci',
           'comment' => '用户角色关联表',
           'id' => false
       ]);

       $table
           ->addColumn('admin_id', 'integer', [
               'null' => false,
               'limit' => 11,
               'comment' => '用户 ID'
           ])
           ->addColumn('role_id', 'integer', [
               'null' => false,
               'limit' => 11,
               'comment' => '角色 ID'
           ]);

       $table->addIndex(['user_id', 'role_id'], [
           'name' => 'user_role_index',
           'unique' => false
       ]);

       $table->create();

       // 记录结束时间
       $endTime = microtime(true);
       // 计算执行时间（秒）
       $executionTime = $endTime - $startTime;
       $executionTime = number_format($executionTime, 6, '.', '');
       $this->output->info("== 创建管理员角色关联表完成用时：{$executionTime}秒");
   }

   private function createAdminPermission(){
        if($this->hasTable('admin_permission'))
        {
            return $this->output->error("=== 管理员权限表已存在 === 跳过");
        }

        $table = $this->table('admin_permission', [
            'engine' => 'InnoDB',
            'collation' => 'utf8mb4_general_ci',
            'comment' => '管理员权限表',
            'id' => 'id',
            'primary_key' => ['id']
        ]);


        $table->addColumn('path' , 'string' , [
            'null' => true,
            'default' => NULL,
            'limit' => 255,
            'comment' => '路由地址',
        ])
            ->addColumn('name' , 'string' ,[
                'null' => false,
                'limit' => 50,
                'comment' => '菜单名称'
            ])
            ->addColumn('parent_id' , 'integer',[
                'comment'   =>  '父级菜单'
            ])
            ->addColumn('component','string' , [
                'null' => true,
                'limit' => 128,
                'comment' => '组件地址'
            ])->addColumn('type','tinyinteger' , [
                'null' => false,
                'default'   =>  1,
                'limit' => 1,
                'comment' => '菜单类型'
            ])
            ->addColumn('perms' , 'string',[
                'null' => false,
                'limit' => 255,
                'comment' => '权限地址'
            ])->addColumn('app' , AdapterInterface::PHINX_TYPE_CHAR,[
                'null' => false,
                'limit' => 32,
                'comment' => '应用名称'
            ])->addColumn('icon' , 'string',[
                'null' => true,
                'limit' => 255,
                'comment' => '图标'
            ])
            ->addColumn('select' , 'string',[
                'null' => true,
                'limit' => 255,
                'comment' => '跳转页'
            ])
            ->addColumn('hidden','tinyinteger' , [
                'null' => false,
                'default'   =>  1,
                'limit' => 1,
                'comment' => '是否显示组件'
            ])
            ->addColumn('create_time', 'integer', [
                'null' => true,
                'default' => NULL,
                'limit' => 11,
                'comment' => '创建时间'
            ])->addColumn('update_time', 'integer', [
                'null' => true,
                'default' => NULL,
                'limit' => 11,
                'comment' => '更新时间'
            ])->addColumn('delete_time', 'integer', [
                'null' => true,
                'default' => NULL,
                'limit' => 11,
                'comment' => '删除时间'
            ]);

        $table->save();

       if ($this->hasTable('admin_permission') && $this->isMigratingUp())
       {
            $this->output->info("== 执行创建菜单");
           // 记录开始时间
           $startTime = microtime(true);
            $menuItems = [
                ['id' => 1, 'path' => 'workbench',  'name' => '工作台',   'parent_id' => 0,   'component' => 'system/workbench/index',    'type' => 2, 'perms' => '','app' => 'adminapi', 'icon' => '', 'hidden' => 0],
                ['id' => 2, 'path' => 'permission', 'name' => '权限管理', 'parent_id' => 0,   'component' => '',                           'type' => 1, 'perms' => '','app' => 'adminapi', 'icon' => 'ant-icon-UserDeleteOutlined', 'hidden' => 0],
                ['id' => 3, 'path' => 'auth',       'name' => '权限列表', 'parent_id' => 2,   'component' => 'system/permission/auth/index', 'type' => 2, 'perms' => '/adminapi/system.permission/lists','app' => 'adminapi', 'icon' => 'ant-icon-UserOutlined', 'hidden' => 0],
                ['id' => 4, 'path' => '',           'name' => '新增',     'parent_id' => 3,   'component' => '',                          'type' => 3, 'perms' => '/adminapi/system.permission/save','app' => 'adminapi', 'icon' => '', 'hidden' => 0],
                ['id' => 5, 'path' => '',           'name' => '更新',     'parent_id' => 3,   'component' => '', 'type' => 3, 'perms' => '/adminapi/system.permission/update','app' => 'adminapi', 'icon' => '', 'hidden' => 0],
                ['id' => 6, 'path' => '',           'name' => '删除',     'parent_id' => 3,   'component' => '', 'type' => 3, 'perms' => '/adminapi/system.permission/delete','app' => 'adminapi', 'icon' => '', 'hidden' => 0],
                ['id' => 7, 'path' => 'admin',      'name' => '管理员',   'parent_id' => 2,   'component' => 'system/permission/admin/index', 'type' => 2, 'perms' => '/adminapi/system.admin/lists','app' => 'adminapi', 'icon' => 'ant-icon-UserOutlined', 'hidden' => 0],
                ['id' => 8, 'path' => '',          'name' => '新增',     'parent_id' => 7,   'component' => '', 'type' => 3, 'perms' => '/adminapi/system.admin/save','app' => 'adminapi', 'icon' => '', 'hidden' => 0],
                ['id' => 9, 'path' => '',          'name' => '编辑',     'parent_id' => 7,   'component' => '', 'type' => 3, 'perms' => '/adminapi/system.admin/update','app' => 'adminapi', 'icon' => '', 'hidden' => 0],
                ['id' => 10, 'path' => '',          'name' => '删除',     'parent_id' => 7,   'component' => '', 'type' => 3, 'perms' => '/adminapi/system.admin/delete','app' => 'adminapi', 'icon' => '', 'hidden' => 0],
                ['id' => 11, 'path' => '',          'name' => '详情',     'parent_id' => 7,   'component' => '', 'type' => 3, 'perms' => '/adminapi/system.admin/detail','app' => 'adminapi', 'icon' => '', 'hidden' => 0],
                ['id' => 12, 'path' => 'role',      'name' => '角色',     'parent_id' => 2,   'component' => 'system/permission/role/index', 'type' => 2, 'perms' => '/adminapi/system.role/lists','app' => 'adminapi', 'icon' => 'ant-icon-AimOutlined', 'hidden' => 0],
                ['id' => 13, 'path' => '',          'name' => '新增',     'parent_id' => 12,  'component' => null, 'type' => 3, 'perms' => '/adminapi/system.role/save','app' => 'adminapi', 'icon' => '', 'hidden' => 0],
                ['id' => 14, 'path' => '',          'name' => '编辑',     'parent_id' => 12,  'component' => null, 'type' => 3, 'perms' => '/adminapi/system.role/update','app' => 'adminapi', 'icon' => '', 'hidden' => 0],
                ['id' => 15, 'path' => '',          'name' => '删除',     'parent_id' => 12,  'component' => null, 'type' => 3, 'perms' => '/adminapi/system.role/delete','app' => 'adminapi', 'icon' => '', 'hidden' => 0],
                ['id' => 16, 'path' => '',          'name' => '设置权限', 'parent_id' => 12,  'component' => '', 'type' => 3, 'perms' => '/adminapi/system.role/setAuth','app' => 'adminapi', 'icon' => '', 'hidden' => 0]
            
            ];

           $this->table('admin_permission')->insert($menuItems)->save();

           // 记录结束时间
           $endTime = microtime(true);
            // 计算执行时间（秒）
           $executionTime = $endTime - $startTime;
           $executionTime = number_format($executionTime, 6, '.', '');
           $this->output->info("== 创建菜单完成用时：{$executionTime}秒");
        }
        
    
   }


    /**
     * 管理员会话表
     * @return void
     */
    private function createAdminSession(){

        if($this->hasTable('admin_session'))
        {
            return $this->output->error("=== 管理员管理员会话表已存在 === 跳过");
        }

        // 记录开始时间
        $startTime = microtime(true);

        $this->output->writeln("== 执行创建管理员会话表");

        $table  = $this->table('admin_session' , [
            'engine' => 'InnoDB',
            'collation' => 'utf8mb4_general_ci',
            'id' => 'id',
            'primary_key' => ['id'],
            'comment' => '管理员会话表',
        ]);

        $table
            ->addColumn('admin_id' , 'integer' , [
                'null'  =>  false,
                'comment'   =>  '用户id'
            ])

            ->addColumn('terminal', 'tinyinteger', [
                'null' => true,
                'limit' => 11,
                'comment' => '客户端类型：1-pc管理后台 2-mobile手机管理后台'
            ])

            ->addColumn('token' , 'string' , [
                'null'  =>  false,
                'limit'     =>  32,
                'comment'   =>  '令牌',
                'collation'   =>  'utf8mb4_general_ci',
            ])->addColumn('expire_time', 'integer', [
                'null' => true,
                'default' => NULL,
                'limit' => 11,
                'comment' => '到期时间'
            ])->addColumn('update_time', 'integer', [
                'null' => true,
                'default' => NULL,
                'limit' => 11,
                'comment' => '更新时间'
            ])->addColumn('delete_time', 'integer', [
                'null' => true,
                'default' => NULL,
                'limit' => 11,
                'comment' => '删除时间'
            ]);

        $table->addIndex(['admin_id', 'terminal'], [
            'name' => 'admin_id_client',
            'unique' => true,
        ]);

        $table->addIndex('token', [
            'name' => 'token',
            'unique' => true,
        ]);

        $table->create();

        // 记录结束时间
        $endTime = microtime(true);


        // 计算执行时间（秒）
        $executionTime = $endTime - $startTime;
        $executionTime = number_format($executionTime, 6, '.', '');



        $this->output->info("== 创建管理员会话表完成用时：{$executionTime}秒");

    }



    /**
     * 创建管理员角色表
     * @return void
     */
   private function createAdminRole(){

       if($this->hasTable('admin_role'))
       {
           return $this->output->error("=== 管理员角色表已存在 === 跳过");
       }

       // 记录开始时间
       $startTime = microtime(true);

       $this->output->writeln("== 执行创建管理员角色表");

       $table = $this->table('admin_role', [
           'engine' => 'InnoDB',
           'collation' => 'utf8mb4_general_ci',
           'comment' => '管理员角色表',
           'id' => 'id',
           'primary_key' => ['id']
       ]);

       $table
           ->addColumn('name', 'string', [
               'null' => false,
               'limit' => 50,
               'comment' => '角色名称'
           ])
           ->addColumn('description', 'string', [
               'null' => true,
               'limit' => 255,
               'comment' => '角色描述'
           ])
           ->addColumn('status', 'tinyinteger', [
               'null' => true,
               'limit' => 1,
               'comment' => '状态 1：开启 0 关闭'
           ])
           ->addColumn('create_time', 'integer', [
               'null' => true,
               'default' => NULL,
               'limit' => 11,
               'comment' => '创建时间'
           ])->addColumn('update_time', 'integer', [
               'null' => true,
               'default' => NULL,
               'limit' => 11,
               'comment' => '更新时间'
           ])->addColumn('delete_time', 'integer', [
               'null' => true,
               'default' => NULL,
               'limit' => 11,
               'comment' => '删除时间'
           ]);

       $table->addIndex('name', [
           'name' => 'name',
           'unique' => true
       ]);

       $table->create();


       // 记录结束时间
       $endTime = microtime(true);


       // 计算执行时间（秒）
       $executionTime = $endTime - $startTime;
       $executionTime = number_format($executionTime, 6, '.', '');



       $this->output->info("== 创建管理员表完成用时：{$executionTime}秒");
   }


    /**
     * 创建管理员表
     * @return void
     */
   private function createAdminUserTable()
   {
       if($this->hasTable('admin'))
       {
            return $this->output->error("=== 管理员表已存在 === 跳过");
       }

       // 记录开始时间
       $startTime = microtime(true);

       $this->output->writeln("== 开始创建管理员表");

       $table = $this->table('admin' , [
           'engine' => 'InnoDB',
           'collation' => 'utf8mb4_general_ci',
           'comment' => '管理员表',
           'id' => 'id',
           'primary_key' => ['id']
       ]);

       $table
           ->addColumn('username', 'string', [
               'null' => false,
               'limit' => 50,
               'comment' => '用户名'
           ])
           ->addColumn('password', 'string', [
               'null' => false,
               'limit' => 255,
               'comment' => '密码'
           ])
           ->addColumn('salt', 'string', [
               'null' => true,
               'limit' => 64,
               'comment' => '密码盐'
           ])
           ->addColumn('nickname', 'string', [
               'null' => true,
               'limit' => 64,
               'comment' => '昵称'
           ])
           ->addColumn('last_login_time', 'integer', [
               'null' => true,
               'limit' => 11,
               'comment' => '最后登录时间'
           ])
           ->addColumn('last_login_ip', 'string', [
               'null' => true,
               'limit' => 32,
               'comment' => '最后登录ip'
           ])

           ->addColumn('root', 'tinyinteger', [
               'null' => true,
               'limit' => 1,
               'default'=>0,
               'comment' => '是否为超级管理员'
           ])

           ->addColumn('avatar', 'string', [
               'null' => true,
               'limit' => 11,
               'comment' => '头像'
           ])->addColumn('status', 'tinyinteger', [
               'null' => true,
               'limit' => 1,
               'default'=>1,
               'comment' => '状态 1：开启 0 关闭'
           ])

           ->addColumn('multipoint_login' , 'tinyinteger' , [
               'null'  =>  true,
               'limit' =>  1,
               'default'   =>  1,
               'comment'    => '是否支持多处登录：1-是；0-否；'
           ])

           ->addColumn('create_time', 'integer', [
               'null' => true,
               'default' => NULL,
               'limit' => 11,
               'comment' => '创建时间'
           ])->addColumn('update_time', 'integer', [
               'null' => true,
               'default' => NULL,
               'limit' => 11,
               'comment' => '更新时间'
           ])->addColumn('delete_time', 'integer', [
               'null' => true,
               'default' => NULL,
               'limit' => 11,
               'comment' => '删除时间'
           ]);

       $table->addIndex('username', [
           'name' => 'username',
           'unique' => true
       ]);


       $table->create();
       // 记录结束时间
       $endTime = microtime(true);


       // 计算执行时间（秒）
       $executionTime = $endTime - $startTime;
       $executionTime = number_format($executionTime, 6, '.', '');



       if ($this->hasTable('admin') && $this->isMigratingUp())
       {


           $salt = uniqid('matrix_');
           # 插入数据
           $this->table('admin')->insert([
               [
                   'username'     => 'admin',
                   'password'     =>  md5('admin' . $salt),
                   'salt'         =>  $salt,
                   'root'          => 1,
                   'create_time'   =>  time(),
               ]
           ])->save();

           $this->output->info("== 插入管理员账号密码 账号密码为:admin");
       }

       $this->output->info("== 创建管理员表完成用时：{$executionTime}秒");


   }
}